import {OutPutBuffer} from "./output/OutPutBuffer";
import {ColorUtil} from "./utils/ColorUtil";

export class CanvasDrawContext {
    canvas: HTMLCanvasElement;
    context: CanvasRenderingContext2D;
    buffers: OutPutBuffer[];
    width: number = 0;
    height: number = 0;
    halfBoundaryLineSize = 2;
    constructor(canvas: HTMLCanvasElement) {
        this.canvas = canvas;
        this.context = this.canvas.getContext('2d') as CanvasRenderingContext2D;
        this.buffers = [];
    }

    addBuffer(buffer: OutPutBuffer) {
        this.buffers.push(buffer);
        this.resetSize();
        this.render(true);
    }

    private resetSize() {
        let width: number = 0, height = 0;
        for (const buffer of this.buffers) {
            width += buffer.width + 2;
            height = Math.max(buffer.height + 2, height);
        }
        this.width = width;
        this.height = height;
        this.canvas.width = this.width;
        this.canvas.height = this.height;
    }

    render(force: boolean = false) {
        let update = force;
        this.buffers.forEach(buffer => update = buffer.update() || update);
        if (update) {
            let offsetX = 0;
            for (const buffer of this.buffers) {
                // 绘制反色边框
                const color = ColorUtil.colorToString(ColorUtil.reserveColor(buffer.calcBackgroundColor()));
                this.context.beginPath();
                this.context.lineWidth = this.halfBoundaryLineSize * 2;
                this.context.strokeStyle = '#ff00ff';
                console.log('绘制边框：', this.context.strokeStyle, this.context.lineWidth);
                this.context.moveTo(offsetX, 0);
                this.context.lineTo(offsetX + buffer.width + this.halfBoundaryLineSize * 2, 0 );
                this.context.lineTo(offsetX + buffer.width + this.halfBoundaryLineSize * 2, 0 + buffer.height + this.halfBoundaryLineSize * 2 );
                this.context.lineTo(offsetX, 0 + buffer.height + this.halfBoundaryLineSize * 2 );
                this.context.lineTo(offsetX, 0 );
                this.context.closePath();
                this.context.stroke();
                // 绘制buffer内容
                this.context.putImageData(buffer.imageData, offsetX + this.halfBoundaryLineSize, this.halfBoundaryLineSize);
                offsetX += buffer.width;
            }
        }
    }
}